import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { SmsService } from '../sms/sms.service';
import { JwtService } from '@nestjs/jwt';
import { LoginAuthDto } from './dto/login-auth.dto';
import { TencentImService } from '../tencent-im/tencent-im.service';
import { ApiException } from '../common/filter/http-exception/api.exception';
import { ApiErrorCode } from '../common/enums/api-error-code.enum';
import encry from '../utils/crypto';
import { CacheService } from "../cache/cache.service";

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private smsService: SmsService,
    private tencentImService: TencentImService,
    private jwtService: JwtService,
    private cacheService: CacheService,
  ) {}

  /**
   * 用户登录
   * @param loginAuthDto
   */
  async login(loginAuthDto: LoginAuthDto) {
    const { login_type, mobile, password, sms_code } = loginAuthDto;
    if (!login_type)
      throw new ApiException('登录类型不能为空', ApiErrorCode.LOGIN_ERROR);
    if (!mobile)
      throw new ApiException('请输入手机号', ApiErrorCode.LOGIN_ERROR);
    const user = await this.userService.findOne(mobile);
    if (login_type === 'password') {
      if (!password)
        throw new ApiException('请输入密码', ApiErrorCode.LOGIN_ERROR);
      if (user?.password !== encry(password, user.salt))
        throw new ApiException('密码不正确', ApiErrorCode.LOGIN_ERROR);
    } else if (login_type === 'sms') {
      if (!sms_code)
        throw new ApiException('请输入验证码', ApiErrorCode.LOGIN_ERROR);
      const smsCodeValidate = await this.smsService.verify(mobile, sms_code);
      if (!smsCodeValidate)
        throw new ApiException('验证码不正确', ApiErrorCode.LOGIN_ERROR);
    } else {
      throw new ApiException('登陆类型错误', ApiErrorCode.LOGIN_ERROR);
    }
    const UserSig = await this.tencentImService.generateUserSig(user.mobile);
    const payload = { mobile: user.mobile, sub: user.id };
    const token = await this.jwtService.signAsync(payload);
    await this.cacheService.set(`${mobile}Token:`, token, 60 * 60 * 24 * 7);
    return {
      token,
      UserSig,
    };
  }

  /**
   * 退出登录
   * @param mobile
   */
  async logout(mobile: string) {
    await this.cacheService.del(`${mobile}Token:`);
    return '退出成功';
  }
}
